import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:zhibao_flutter/api/mine/mine_view_model.dart';
import 'package:zhibao_flutter/api/user/user_view_model.dart';
import 'package:zhibao_flutter/pages/home/bubble_new_page.dart';
import 'package:zhibao_flutter/pages/mine/bill/bill_logic.dart';
import 'package:zhibao_flutter/pages/mine/bill/bill_view.dart';
import 'package:zhibao_flutter/test/about_page.dart';
import 'package:zhibao_flutter/test/set_page.dart';
import 'package:zhibao_flutter/util/config/config_route.dart';
import 'package:zhibao_flutter/util/data/q1_data.dart';
import 'package:zhibao_flutter/util/event_bus/avatar_refresh_event.dart';
import 'package:zhibao_flutter/util/ui/my_toast.dart';
import 'package:zhibao_flutter/widget/dialog/confirm_alert.dart';
import 'package:zhibao_flutter/widget/dialog/confirm_dialog.dart';
import 'package:zhibao_flutter/zone.dart';

class MineLogic extends GetxController {
  RefreshController refreshController = RefreshController();

  StreamSubscription? eventBusOfRefreshAvatarValue;

  List<List<String>> get items => [
    ['ic_mine_item_team.svg', "myTeam".tr],
    ['ic_mine_item_team.svg', "myMatrix".tr],
    ['ic_mine_item_charge.svg', "assetDetails".tr],
    ['ic_mine_item_invite.svg', "inviteFriends".tr],
    ['ic_mine_item_u_transform.svg', "pointsTransfer".tr],
    ['ic_mine_item_switch_lan.svg', "languageSwitch".tr],
  ];

  List<List<String>> get itemsOfHide => [
    ['ic_mine_item_invite.svg', "usageInstructions".tr],
    ['ic_mine_item_invite.svg', "privacyPolicy".tr],
    ['ic_mine_item_invite.svg', "changePassword".tr],
    ['ic_mine_item_invite.svg', "aboutUs".tr],
    ['ic_mine_item_invite.svg', "settings".tr],
  ];

  Worker? worker;

  @override
  void onInit() {
    super.onInit();
    refreshMine();

    eventBusOfRefreshAvatarValue =
        avatarRefreshBus.on<AvatarRefreshModel>().listen((event) {
      update();
      myToast("operationSuccessful".tr);

      /// 一般在这刷新都是上传头像之后
      // refreshMine().then((value) {
      //   myToast("操作成功");
      // });
    });

    worker = ever(AppConfig.currentLan, (callback) {
      refreshMine();
      update();
    });
  }

  Future refreshMine() async {
    try {
      await mineViewModel.getSelfInfo(null, Q1Data.loginRspEntity!.token!);
      refreshController.refreshCompleted();
      update();
    } catch (e) {
      LogUtil.d("MineLogic refresh error: $e");
      refreshController.refreshCompleted();
      update();
    }
  }

  void onItemClick(String v) {
    if (v == "usageInstructions".tr) {
      Get.to(MyScaffold(
        appBar: CommomBar(title: "usageInstructions".tr),
        bottomSheet: Container(
          width: Get.width,
          height: 80.px,
          alignment: Alignment.center,
          padding: EdgeInsets.symmetric(vertical: 20.px),
          child: SmallButton(
            width: 180.px,
            onPressed: () {
              Get.back();
            },
            child: Text('back'.tr),
          ),
        ),
        body: ListView(
          padding: EdgeInsets.all(10.px),
          children: [
            SelectableText(
              """这是一款多功能工具类办公类应用， ${AppConfig.appName}功能非常的完善强大，亦被诸多媒体所报道。 ${AppConfig.appName}好在哪里，为什么被用户如此喜爱?

· 强大
${AppConfig.appName}提供了与文字、计算、查询、相关的多种工具，基本满足您在日常使用手机时的所有工具需求。
丰富的功能模块提高您的工作效率，并使您可以不用再经常寻找下载一些不怎么常用的工具app，让设备更加纯净。

· 纯粹
无推送，无后台唤醒，从不再您不需要的时候打扰到您。简明纯粹的主页与分类，让您在众多的功能中不会眼花缭乱，只关心您喜爱的事物。

· 美好
在关于${AppConfig.appName}的设计与交互上，我们向来坚守简明纯粹的实用主义美学，并跟随Google的MaterialDesign潮流，在细节上执着到一个像素也不放过的地步。

我们深信，认真美好的设计是对人性的关怀，也是让用户一见钟情的利器。

· 结语
如果你觉得有缺少或者有更好的建议也可以反馈给我们，
如果我们觉得可取将会添加工具到列表，或者下个版本发布到app，您可以实时关注动态。
""",
              // '  ${AppConfig.appName}是一个工具平台，在这里可以拥有你自己的专属工具箱，'
              // '如果你觉得有缺少或者有更好的建议也可以反馈给我们，'
              // '如果我们觉得可取将会添加工具到列表，或者下个版本发布到app，'
              // '您可以实时关注动态。',
              style: TextStyle(
                color: Colors.black,
                fontSize: 14.px,
              ),
            ),
            SizedBox(height: 70.px),
          ],
        ),
      ));
    } else if (v == "settings".tr) {
      Get.to(SetPage());
    } else if (v == "changePassword".tr) {
      Get.toNamed(RouteConfig.forgetPwPage, arguments: true);
    } else if (v == "privacyPolicy".tr) {
      Get.toNamed(RouteConfig.privacyPage);
    } else if (v == "aboutUs".tr) {
      Get.to(AboutPage());
    } else if (v == "myTeam".tr) {
      Get.toNamed(RouteConfig.teamPage);
    } else if (v == "myMatrix".tr) {
      Get.to(BubbleNewPage());
    } else if (v == "assetDetails".tr) {
      Get.toNamed(RouteConfig.billPage, arguments: {
        // [Bill page] Pass null will be display first tab as default.
        BillConfig.useParamKey: null,
      });
    } else if (v == "transferOut".tr) {
      Get.toNamed(RouteConfig.withdrawPage);
    } else if (v == "goUpgrade".tr) {
      Get.toNamed(RouteConfig.upgradePage);
    } else if (v == "walletAddress".tr) {
      Get.toNamed(RouteConfig.chargePage);
    } else if (v == "transferRecord".tr) {
      Get.toNamed(RouteConfig.billPage, arguments: {
        BillConfig.useParamKey: BillTypeFromEnum.withdraw,
      });
    } else if (v == "inviteFriends".tr) {
      Get.toNamed(RouteConfig.invitePage);
    } else if (v == "pointsTransfer".tr) {
      Get.toNamed(RouteConfig.transferPage);
    } else if (v == "languageSwitch".tr) {
      Get.toNamed(RouteConfig.languageSetPage);
    }
  }

  void logout(BuildContext context) {
    confirmDialog(context, text: "logoutConfirmation".tr, onPressed: () {
      userViewModel.loginOut();
    });
  }

  @override
  void onClose() {
    super.onClose();
    eventBusOfRefreshAvatarValue?.cancel();
    eventBusOfRefreshAvatarValue = null;
    worker?.dispose();
    worker = null;
  }
}
